package com.infore.qualityControl.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.chainsaw.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.infore.qualityControl.bo.QualityParamSelectBo;
import com.infore.qualityControl.constant.Constants;
import com.infore.qualityControl.entity.ArtificialData;
import com.infore.qualityControl.entity.MonthQualityIntegrated;
import com.infore.qualityControl.entity.MonthQualityMultipoint;
import com.infore.qualityControl.entity.SysUser;
import com.infore.qualityControl.enums.CQQualitySpecificationEnum;
import com.infore.qualityControl.enums.QualityProjectEnum;
import com.infore.qualityControl.enums.ResultStatus;
import com.infore.qualityControl.po.FiveParameter;
import com.infore.qualityControl.po.IntegratedIntervention;
import com.infore.qualityControl.po.MultipointLinearity;
import com.infore.qualityControl.po.RealWaterSampleComparison;
import com.infore.qualityControl.po.Recovery;
import com.infore.qualityControl.po.SpanDrift;
import com.infore.qualityControl.po.VerificationOfStandardSample;
import com.infore.qualityControl.po.ZeroDrift;
import com.infore.qualityControl.remoteEntity.CheckData;
import com.infore.qualityControl.remoteEntity.RealTimeData;
import com.infore.qualityControl.remoteEntity.RecoveryData;
import com.infore.qualityControl.remoteEntity.SpanCheckData;
import com.infore.qualityControl.remoteEntity.ZeroCheckData;
import com.infore.qualityControl.remoteService.IDataReceivingService;
import com.infore.qualityControl.remoteService.ISiteManageService;
import com.infore.qualityControl.remoteService.ISysUserService;
import com.infore.qualityControl.repository.IFiveParameterRepository;
import com.infore.qualityControl.repository.IMultipointLinearityRepository;
import com.infore.qualityControl.repository.IMonthQualityMultipointRepository;
import com.infore.qualityControl.repository.IRealWaterSampleComparisonRepository;
import com.infore.qualityControl.repository.IRecoveryRepository;
import com.infore.qualityControl.repository.ISpanDriftRepository;
import com.infore.qualityControl.repository.IVerificationOfStandardSampleRepository;
import com.infore.qualityControl.repository.IZeroDriftRepository;
import com.infore.qualityControl.repository.IIntegratedInterventionRepository;
import com.infore.qualityControl.select.dto.QueryParamDto;
import com.infore.qualityControl.service.ICQCreateQualityDataService;
import com.infore.qualityControl.service.IQualityControlSetService;
import com.infore.qualityControl.util.DateUtil;
import com.infore.qualityControl.util.JsonUtils;
import com.infore.qualityControl.util.ObjectMapperUtil;
import com.infore.qualityControl.util.CQQualityDataUtil;
import com.infore.qualityControl.util.RedisUtil;
import com.infore.qualityControl.util.ResultEntity;
import com.infore.qualityControl.util.ResultEntityUtil;
import com.infore.qualityControl.util.SmsUtil;
import com.infore.qualityControl.util.TheleastsquaremethodUtils;
import com.infore.qualityControl.util.WarnUtil;

@Service
public class CQCreateQualityDataServiceImpl implements ICQCreateQualityDataService {

	private static final Logger logger = LoggerFactory.getLogger(CQCreateQualityDataServiceImpl.class);

	@Autowired
	IDataReceivingService IDataReceivingService;

	@Autowired
	ISysUserService ISysUserService;

	@Autowired
	IMultipointLinearityRepository IMultipointLinearityRepository;

	@Autowired
	IIntegratedInterventionRepository IIntegratedInterventionRepository;

	@Autowired
	ISiteManageService ISiteManageService;

	@Autowired
	IQualityControlSetService IQualityControlSetService;

	@Autowired
	IRealWaterSampleComparisonRepository IRealWaterSampleComparisonRepository;

	@Autowired
	IMonthQualityMultipointRepository IMonthQualityMultipointRepository;

	@Autowired
	ObjectMapperUtil objectMapperUtil;

	@Autowired
	RedisUtil RedisUtil;

	@Autowired
	IZeroDriftRepository iZeroDriftRepository;

	@Autowired
	ISpanDriftRepository iSpanDriftRepository;

	@Autowired
	IFiveParameterRepository iFiveParameterRepository;

	@Autowired
	IRecoveryRepository iRecoveryRepository;

	@Autowired
	IVerificationOfStandardSampleRepository iVerificationOfStandardSampleRepository;

	public static final String QUALIFIED = "合格";
	public static final String NO_QUALIFIED = "不合格";
	public static final String DATA_FLAG = "N";
	public static final String FLAG = "-";

	public static final Integer ORACLE_IN_MAX = 1000; // oracle in 参数最大个数

	@SuppressWarnings("unchecked")
	@Override
	public void createZeroCheckData(String factorCode) {
		ResultEntity resultEntity = IDataReceivingService.queryZeroCheckData(factorCode);
		if (resultEntity.getCode() == 1) {
			System.out.println("获取零点核查初始数据失败！");
		}
		List<ZeroCheckData> list = objectMapperUtil.convertList(resultEntity, ZeroCheckData.class);
		// 先封装因子+时间,测定值的数据结构
		List<Map<String, Object>> indexTimeList = new ArrayList<Map<String, Object>>();
		for (ZeroCheckData zeroCheckData : list) {
			String stationCode = zeroCheckData.getMn();
			String indexCode = zeroCheckData.getFactorCode();
			String value = zeroCheckData.getCheckData(); // 测定值
			Date timestamp = zeroCheckData.getDataTime();
			Map<String, Object> map = new HashMap<String, Object>();
			if ("".equals(value) || value == null) {
				map.put(stationCode + indexCode + timestamp, null);
			} else {
				map.put(stationCode + indexCode + timestamp, Double.valueOf(value));
			}
			indexTimeList.add(map);
		}
		// 获取缓存数据
		List<Object> redisList = RedisUtil.lGet("zeroValue", 0, -1);
		List<Map<String, Object>> valueList = new ArrayList<Map<String, Object>>();
		if (redisList != null && redisList.size() > 0) {
			valueList = (List<Map<String, Object>>) redisList.get(0);
		}
		// 将缓存的数据添加到新的匹配数据中
		indexTimeList.addAll(valueList);
		List<String> idList = new ArrayList<String>();
		// 获取站点相关信息
		Map<String, Map<String, Object>> siteMap = this.getStationMsg();
		// 获取站点配置的质控参数信息
		List<Map<String, Map<String, Object>>> allDayQualityControlParam = IQualityControlSetService
				.currentAllDayQualityControlParam();
		// 遍历封装创建零点数据
		for (int i = 0; i < list.size(); i++) {
			String id = list.get(i).getId();
			idList.add(id);
			String stationCode = list.get(i).getMn();
			String indexCode = list.get(i).getFactorCode();
			Double value = null;
			if (list.get(i).getCheckData() != null) {
				value = Double.valueOf(list.get(i).getCheckData()); // 测定值
			}
			String standardSamplesValue = list.get(i).getStandardValue(); // 标样值
			String spanValue = list.get(i).getSpanValue(); // 跨度值
			if ("".equals(spanValue) || "0".equals(spanValue) || spanValue == null || "0".equals(standardSamplesValue)
					|| "".equals(standardSamplesValue) || standardSamplesValue == null) { // 如果跨度值、标样值为空,则需要使用配置的跨度值参数
				for (Map<String, Map<String, Object>> map : allDayQualityControlParam) {
					Map<String, Object> indexMap = map.get(stationCode);
					if (indexMap == null) {
						continue;
					} else if ("".equals(spanValue) || "0".equals(spanValue) || spanValue == null) {
						spanValue = indexMap.get(indexCode + "spanValue") == null ? null
								: indexMap.get(indexCode + "spanValue").toString();
					} else if ("".equals(standardSamplesValue) || "0".equals(standardSamplesValue)
							|| standardSamplesValue == null) {
						standardSamplesValue = indexMap.get(indexCode + "zeroStandardValue") == null ? null
								: indexMap.get(indexCode + "zeroStandardValue").toString();
					}
					if ((!"".equals(spanValue) && !"0".equals(spanValue) && spanValue != null)
							|| (!"".equals(standardSamplesValue) && !"0".equals(standardSamplesValue)
									&& standardSamplesValue != null)) {
						break;
					}
				}
			}
//			String flag = list.get(i).getFlag();
			Date timestamp = list.get(i).getDataTime();
//			if (DATA_FLAG.equals(flag)) {
			// 修约测定值
//				if (value != null) {
//					value = CQQualityDataUtil.scaleData(indexCode, value);
//				}
			// 计算绝对误差
			String absoluteError = FLAG;
			if (value != null && standardSamplesValue != null) {
				absoluteError = CQQualityDataUtil.zeroCheckAbsoluteError(value, Double.valueOf(standardSamplesValue),
						indexCode);
			}
			// 计算相对误差
			String relativeError = FLAG;
			String lastDayZeroValue = FLAG;
			// 获取前一天的时间
			Date lastDate = new Timestamp(
					DateUtil.stringToDate(DateUtil.addDate(DateUtil.dateToString(timestamp, DateUtil.DATE_SMALL_YMDHMS),
							-1, DateUtil.DATE_SMALL_YMDHMS), DateUtil.DATE_SMALL_YMDHMS).getTime());
			// 通过监测项与时间键值对找出上一天的测定值
			for (Map<String, Object> map : indexTimeList) {
				lastDayZeroValue = map.get(stationCode + indexCode + lastDate) == null ? FLAG
						: map.get(stationCode + indexCode + lastDate).toString();
				if (!FLAG.equals(lastDayZeroValue)) {
					if (value != null && spanValue != null) {
						relativeError = CQQualityDataUtil.zeroDriftRelativeError(value,
								Double.valueOf(lastDayZeroValue), Double.valueOf(spanValue));
					}
					break;
				}
			}
			// 判断零点核查是否合格(绝对误差是否在技术要求之内)
			String checkQualification = NO_QUALIFIED;
			String absoluteTechnicalRequirement = "";
			if (indexCode.equals(QualityProjectEnum.IMN.getCode())) {
				if (!FLAG.equals(absoluteError)
						&& Double.valueOf(absoluteError) >= CQQualitySpecificationEnum.ZERO_CHECK_IMN.getLower()
						&& Double.valueOf(absoluteError) <= CQQualitySpecificationEnum.ZERO_CHECK_IMN.getUpper()) {
					checkQualification = QUALIFIED;
				}
				absoluteTechnicalRequirement = CQQualitySpecificationEnum.ZERO_CHECK_IMN.getScope();
			} else if (indexCode.equals(QualityProjectEnum.NH3.getCode())) {
				if (!FLAG.equals(absoluteError)
						&& Double.valueOf(absoluteError) >= CQQualitySpecificationEnum.ZERO_CHECK_NH3.getLower()
						&& Double.valueOf(absoluteError) <= CQQualitySpecificationEnum.ZERO_CHECK_NH3.getUpper()) {
					checkQualification = QUALIFIED;
				}
				absoluteTechnicalRequirement = CQQualitySpecificationEnum.ZERO_CHECK_NH3.getScope();
			} else if (indexCode.equals(QualityProjectEnum.TP.getCode())) {
				if (!FLAG.equals(absoluteError)
						&& Double.valueOf(absoluteError) >= CQQualitySpecificationEnum.ZERO_CHECK_TP.getLower()
						&& Double.valueOf(absoluteError) <= CQQualitySpecificationEnum.ZERO_CHECK_TP.getUpper()) {
					checkQualification = QUALIFIED;
				}
				absoluteTechnicalRequirement = CQQualitySpecificationEnum.ZERO_CHECK_TP.getScope();
			} else if (indexCode.equals(QualityProjectEnum.TN.getCode())) {
				if (!FLAG.equals(absoluteError)
						&& Double.valueOf(absoluteError) >= CQQualitySpecificationEnum.ZERO_CHECK_TN.getLower()
						&& Double.valueOf(absoluteError) <= CQQualitySpecificationEnum.ZERO_CHECK_TN.getUpper()) {
					checkQualification = QUALIFIED;
				}
				absoluteTechnicalRequirement = CQQualitySpecificationEnum.ZERO_CHECK_TN.getScope();
			} else if (indexCode.equals(QualityProjectEnum.COD.getCode())) {
				if (!FLAG.equals(absoluteError)
						&& Double.valueOf(absoluteError) >= CQQualitySpecificationEnum.ZERO_CHECK_COD.getLower()
						&& Double.valueOf(absoluteError) <= CQQualitySpecificationEnum.ZERO_CHECK_COD.getUpper()) {
					checkQualification = QUALIFIED;
				}
				absoluteTechnicalRequirement = CQQualitySpecificationEnum.ZERO_CHECK_COD.getScope();
			}
			// 判断零点漂移是否合格(相对误差是否在技术要求之内)
			String driftQualification = NO_QUALIFIED;
			if (!FLAG.equals(relativeError)) {
				if (Double.valueOf(relativeError) >= CQQualitySpecificationEnum.ZERO_DRIFT.getLower()
						&& Double.valueOf(relativeError) <= CQQualitySpecificationEnum.ZERO_DRIFT.getUpper()) {
					driftQualification = QUALIFIED;
				}
			}
			// 初始化实体类
			ZeroDrift zeroDrift = new ZeroDrift();
			zeroDrift.setStationCode(stationCode);
			zeroDrift.setStationName(siteMap.get(stationCode).get("stationName").toString());
			zeroDrift.setBasinCode(siteMap.get(stationCode).get("basinn_basinnCode").toString());
			zeroDrift.setBasinName(siteMap.get(stationCode).get("basinn_basinnName").toString());
			zeroDrift.setAreaCode(siteMap.get(stationCode).get("area_areaCode").toString());
			zeroDrift.setAreaName("重庆市");

//				if ("40000000000001".equals(stationCode)) { // 水站1
//					zeroDrift.setStationName("水站1");
//					zeroDrift.setBasinCode("C001");
//					zeroDrift.setBasinName("长江流域");
//					zeroDrift.setAreaCode("001");
//					zeroDrift.setAreaName("测试区");
//				} else if ("40000000000002".equals(stationCode)) { // 水站2
//					zeroDrift.setStationName("水站2");
//					zeroDrift.setBasinCode("C001");
//					zeroDrift.setBasinName("长江流域");
//					zeroDrift.setAreaCode("001");
//					zeroDrift.setAreaName("测试区");
//				} else if ("40000000000003".equals(stationCode)) { // 污染源站点1
//					zeroDrift.setStationName("污染源站点1");
//					zeroDrift.setBasinCode("C001");
//					zeroDrift.setBasinName("长江流域");
//					zeroDrift.setAreaCode("001");
//					zeroDrift.setAreaName("测试区");
//				} else {
//					zeroDrift.setStationName("测试站");
//					zeroDrift.setBasinCode("A430100");
//					zeroDrift.setBasinName("测试流域");
//					zeroDrift.setAreaCode("001");
//					zeroDrift.setAreaName("测试区");
//				}
			zeroDrift.setIndexCode(indexCode);
			zeroDrift.setIndexName(QualityProjectEnum.getName(indexCode));
			zeroDrift.setIndexUnit(QualityProjectEnum.getUnit(indexCode));
			zeroDrift.setTime(timestamp);
			zeroDrift.setValue(value == null ? "" : value.toString());
			zeroDrift.setLastValue(lastDayZeroValue);
			zeroDrift.setStandardSamplesValue(standardSamplesValue);
			zeroDrift.setSpanValue(spanValue);
			zeroDrift.setAbsoluteError(absoluteError);
			zeroDrift.setRelativeError(relativeError);
			zeroDrift.setQualification(checkQualification);
			zeroDrift.setLastQualification(driftQualification);
			// 获取各因子的技术标准范围
			zeroDrift.setAbsoluteTechnicalRequirement(absoluteTechnicalRequirement);
			zeroDrift.setRelativeTechnicalRequirement(CQQualitySpecificationEnum.ZERO_DRIFT.getScope());
			try {
				iZeroDriftRepository.saveAndFlush(zeroDrift);
			} catch (Exception e) {
				Throwable cause = e.getCause();
				logger.info("@@@零点漂移发生异常：" + ((org.hibernate.exception.ConstraintViolationException)cause).getSQLException().getMessage());
			}
//			}
		}
		// 每次都清空上一次缓存数据
		RedisUtil.del("zeroValue");
		// 设置缓存(是将list数据保存至缓存中的list中,故上述取值时取list中第一个)
		List<Map<String, Object>> zeroRedisList = new ArrayList<Map<String, Object>>();
		zeroRedisList.addAll(indexTimeList);
		RedisUtil.lSet("zeroValue", zeroRedisList);
		logger.info("@@@idList的大小" + idList.size());
		if (!idList.isEmpty()) {
			int part = idList.size() / 800; // 分批数
			logger.info("共有 ： " + idList.size() + "条");
			for (int i = 0; i <= part; i++) {
				int j = 800 * (i + 1);
				if (i == part) {
					j = idList.size();
				}
				logger.info("@@@开始执行updateZeroCheckData");
				IDataReceivingService.updateZeroCheckData(idList.subList(800 * i, j));
			}
			logger.info("@@@update执行结束");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void createSpanCheckData(String factorCode) {
		ResultEntity resultEntity = IDataReceivingService.querySpanCheckData(factorCode);
		if (resultEntity.getCode() == 1) {
			System.out.println("获取跨度核查初始数据失败！");
		}
		List<SpanCheckData> list = objectMapperUtil.convertList(resultEntity, SpanCheckData.class);
		// 先封装因子+时间,测定值的数据结构
		List<Map<String, Object>> indexTimeList = new ArrayList<Map<String, Object>>();
		for (SpanCheckData spanCheckData : list) {
			String stationCode = spanCheckData.getMn();
			String indexCode = spanCheckData.getFactorCode();
			String value = spanCheckData.getCheckData(); // 测定值
			Date timestamp = spanCheckData.getDataTime();
			Map<String, Object> map = new HashMap<String, Object>();
			if ("".equals(value) || value == null) {
				map.put(stationCode + indexCode + timestamp, null);
			} else {
				map.put(stationCode + indexCode + timestamp, Double.valueOf(value));
			}
			indexTimeList.add(map);
		}
		// 获取缓存数据
		List<Object> redisList = RedisUtil.lGet("spanValue", 0, -1);
		List<Map<String, Object>> valueList = new ArrayList<Map<String, Object>>();
		if (redisList != null && redisList.size() > 0) {
			valueList = (List<Map<String, Object>>) redisList.get(0);
		}
		// 将缓存的数据添加到新的匹配数据中
		indexTimeList.addAll(valueList);
		List<String> idList = new ArrayList<String>();
		// 获取站点相关信息
		Map<String, Map<String, Object>> siteMap = this.getStationMsg();
		// 获取站点配置的质控参数信息
		List<Map<String, Map<String, Object>>> allDayQualityControlParam = IQualityControlSetService
				.currentAllDayQualityControlParam();
		// 遍历封装创建跨度数据
		for (int i = 0; i < list.size(); i++) {
			String id = list.get(i).getId();
			idList.add(id);
			String stationCode = list.get(i).getMn();
			String indexCode = list.get(i).getFactorCode();
			Double value = null;
			if (list.get(i).getCheckData() != null) {
				value = Double.valueOf(list.get(i).getCheckData()); // 测定值
			}
//			Double standardSamplesValue = null;
//			if (list.get(i).getStandardValue() != null) {
//				standardSamplesValue = Double.valueOf(list.get(i).getStandardValue()); // 标样值
//			}
			String standardSamplesValue = list.get(i).getStandardValue(); // 标样值
			String spanValue = list.get(i).getSpanValue(); // 跨度值
			if ("".equals(spanValue) || "0".equals(spanValue) || spanValue == null
					|| "0.00".equals(standardSamplesValue) || "".equals(standardSamplesValue)
					|| standardSamplesValue == null) { // 如果跨度值、标样值为空,则需要使用配置的跨度值参数
				for (Map<String, Map<String, Object>> map : allDayQualityControlParam) {
					Map<String, Object> indexMap = map.get(stationCode);
					if (indexMap == null) {
						continue;
					} else if ("".equals(spanValue) || "0".equals(spanValue) || spanValue == null) {
						spanValue = indexMap.get(indexCode + "spanValue") == null ? null
								: indexMap.get(indexCode + "spanValue").toString();
					} else if ("".equals(standardSamplesValue) || "0.00".equals(standardSamplesValue)
							|| standardSamplesValue == null) {
						standardSamplesValue = indexMap.get(indexCode + "spanStandardValue") == null ? null
								: indexMap.get(indexCode + "spanStandardValue").toString();
					}
					if ((!"".equals(spanValue) && !"0".equals(spanValue) && spanValue != null)
							|| (!"".equals(standardSamplesValue) && !"0.00".equals(standardSamplesValue)
									&& standardSamplesValue != null)) {
						break;
					}
				}
			}
//			String flag = list.get(i).getFlag();
			Date timestamp = list.get(i).getDataTime();
//			if (DATA_FLAG.equals(flag)) {
			// 修约测定值
//				if (value != null) {
//					value = CQQualityDataUtil.scaleData(indexCode, value);
//				}
			// 计算核查相对误差
			String checkRelativeError = FLAG;
			if (value != null && standardSamplesValue != null) {
				checkRelativeError = CQQualityDataUtil.spanCheckRelativeError(value,
						Double.valueOf(standardSamplesValue), indexCode);
			}
			// 计算漂移相对误差
			String driftRelativeError = FLAG;
			String lastDaySpanValue = FLAG;
			// 获取前一天的时间
			Date lastDate = new Timestamp(
					DateUtil.stringToDate(DateUtil.addDate(DateUtil.dateToString(timestamp, DateUtil.DATE_SMALL_YMDHMS),
							-1, DateUtil.DATE_SMALL_YMDHMS), DateUtil.DATE_SMALL_YMDHMS).getTime());
			// 通过检测项与时间键值对找出前一天的测定值
			for (Map<String, Object> map : indexTimeList) {
				lastDaySpanValue = map.get(stationCode + indexCode + lastDate) == null ? FLAG
						: map.get(stationCode + indexCode + lastDate).toString();
				if (!FLAG.equals(lastDaySpanValue)) {
					if (value != null && spanValue != null) {
						driftRelativeError = CQQualityDataUtil.spanDriftRelativeError(value,
								Double.valueOf(lastDaySpanValue), Double.valueOf(spanValue));
					}
					break;
				}
			}
			// 判断跨度核查是否合格(相对误差是否在技术要求之内)
			String checkQualification = NO_QUALIFIED;
			if (!FLAG.equals(checkRelativeError)) {
				if (Double.valueOf(checkRelativeError) >= CQQualitySpecificationEnum.SPAN_CHECK.getLower()
						&& Double.valueOf(checkRelativeError) <= CQQualitySpecificationEnum.SPAN_CHECK.getUpper()) {
					checkQualification = QUALIFIED;
				}
			}
			// 判断跨度漂移是否合格(相对误差是否在技术要求之内)
			String driftQualification = NO_QUALIFIED;
			if (!FLAG.equals(driftRelativeError)) {
				if (Double.valueOf(driftRelativeError) >= CQQualitySpecificationEnum.SPAN_DRIFT.getLower()
						&& Double.valueOf(driftRelativeError) <= CQQualitySpecificationEnum.SPAN_DRIFT.getUpper()) {
					driftQualification = QUALIFIED;
				}
			}
			// 初始化实体类
			SpanDrift spanDrift = new SpanDrift();
			spanDrift.setStationCode(stationCode);
			spanDrift.setStationName(siteMap.get(stationCode).get("stationName").toString());
			spanDrift.setBasinCode(siteMap.get(stationCode).get("basinn_basinnCode").toString());
			spanDrift.setBasinName(siteMap.get(stationCode).get("basinn_basinnName").toString());
			spanDrift.setAreaCode(siteMap.get(stationCode).get("area_areaCode").toString());
			spanDrift.setAreaName("重庆市");
//				if ("40000000000001".equals(stationCode)) { // 水站1
//					spanDrift.setStationName("水站1");
//					spanDrift.setBasinCode("C001");
//					spanDrift.setBasinName("长江流域");
//					spanDrift.setAreaCode("001");
//					spanDrift.setAreaName("测试区");
//				} else if ("40000000000002".equals(stationCode)) { // 水站2
//					spanDrift.setStationName("水站2");
//					spanDrift.setBasinCode("C001");
//					spanDrift.setBasinName("长江流域");
//					spanDrift.setAreaCode("001");
//					spanDrift.setAreaName("测试区");
//				} else if ("40000000000003".equals(stationCode)) { // 污染源站点1
//					spanDrift.setStationName("污染源站点1");
//					spanDrift.setBasinCode("C001");
//					spanDrift.setBasinName("长江流域");
//					spanDrift.setAreaCode("001");
//					spanDrift.setAreaName("测试区");
//				} else {
//					spanDrift.setStationName("测试站");
//					spanDrift.setBasinCode("A430100");
//					spanDrift.setBasinName("测试流域");
//					spanDrift.setAreaCode("001");
//					spanDrift.setAreaName("测试区");
//				}
			spanDrift.setIndexCode(indexCode);
			spanDrift.setIndexName(QualityProjectEnum.getName(indexCode));
			spanDrift.setIndexUnit(QualityProjectEnum.getUnit(indexCode));
			spanDrift.setTime(timestamp);
			spanDrift.setValue(value == null ? "" : value.toString());
			spanDrift.setLastValue(lastDaySpanValue);
			spanDrift.setStandardSamplesValue(standardSamplesValue == null ? "" : standardSamplesValue.toString());
			spanDrift.setSpanValue(spanValue);
			spanDrift.setCheckRelativeError(checkRelativeError);
			spanDrift.setDriftRelativeError(driftRelativeError);
			spanDrift.setQualification(checkQualification);
			spanDrift.setLastQualification(driftQualification);
			spanDrift.setCheckTechnicalRequirement(CQQualitySpecificationEnum.SPAN_CHECK.getScope());
			spanDrift.setDriftTechnicalRequirement(CQQualitySpecificationEnum.SPAN_DRIFT.getScope());
			try {
				iSpanDriftRepository.saveAndFlush(spanDrift);
			} catch (Exception e) {
				Throwable cause = e.getCause();
				logger.info("@@@跨度漂移发生异常：" + ((org.hibernate.exception.ConstraintViolationException)cause).getSQLException().getMessage());
			}
//			}
		}
		// 每次都清空上一次缓存数据
		RedisUtil.del("spanValue");
		// 设置缓存(是将list数据保存至缓存中的list中,故上述取值时取list中第一个)
		List<Map<String, Object>> spanRedisList = new ArrayList<Map<String, Object>>();
		spanRedisList.addAll(indexTimeList);
		RedisUtil.lSet("spanValue", spanRedisList);
		logger.info("@@@idList的大小" + idList.size());
		if (!idList.isEmpty()) {
			int part = idList.size() / 800; // 分批数
			logger.info("共有 ： " + idList.size() + "条");
			for (int i = 0; i <= part; i++) {
				int j = 800 * (i + 1);
				if (i == part) {
					j = idList.size();
				}
				logger.info("@@@开始执行updateSpanCheckData");
				IDataReceivingService.updateSpanCheckData(idList.subList(800 * i, j));
			}
			logger.info("@@@update执行结束");
		}
	}

	@Override
	public void createCheckData() {
		// 获取站点相关信息
		Map<String, Map<String, Object>> siteMap = this.getStationMsg();
		// 获取站点配置的质控参数信息
		List<Map<String, Map<String, Object>>> allMonthQualityControlStandardParam = IQualityControlSetService
				.currentMonthQualityControlStandardCheckParam();
		ResultEntity resultEntity = IDataReceivingService.queryCheckData();
		if (resultEntity.getCode() == 1) {
			System.out.println("获取标样初始数据失败！");
		}
		List<CheckData> list = objectMapperUtil.convertList(resultEntity, CheckData.class);
		List<String> idList = new ArrayList<String>();
		for (CheckData checkData : list) {
			String id = checkData.getId();
			idList.add(id);
			String stationCode = checkData.getMn();
			String indexCode = checkData.getFactorCode();
			String dataFlag = checkData.getFlag();
			Double value = null;
			if (checkData.getCheckData() != null) {
				value = Double.valueOf(checkData.getCheckData()); // 测定值
			}
			String standardSamplesValue = null;
			if (checkData.getStandardValue() != null) {
				standardSamplesValue = checkData.getStandardValue(); // 标样标准浓度值
			} else {
				for (Map<String, Map<String, Object>> map : allMonthQualityControlStandardParam) {
					Map<String, Object> indexMap = map.get(stationCode);
					standardSamplesValue = indexMap.get(indexCode).toString();
					if (!"".equals(standardSamplesValue) && standardSamplesValue != null) {
						break;
					}
				}
			}
			Date timestamp = checkData.getDataTime();
//			String flag = checkData.getFlag();
			if (!"w01010".equals(indexCode)) {
				// 修约测定值
//				if (value != null) {
//					value = CQQualityDataUtil.scaleData(indexCode, value);
//				}
				// 计算误差
				String error = FLAG;
				if (value != null && standardSamplesValue != null) {
					error = CQQualityDataUtil.verificationOfStandardSamplesError(value,
							Double.valueOf(standardSamplesValue), indexCode);
				}
				// 判断是否合格及对应的技术标准
				String qualification = NO_QUALIFIED;
				String technicalRequirement = "-";
				if (indexCode.equals(QualityProjectEnum.PH.getCode())) {
					if (!FLAG.equals(error)
							&& Double.valueOf(error) >= CQQualitySpecificationEnum.STANDARD_CQ_CHECK_PH.getLower()
							&& Double.valueOf(error) <= CQQualitySpecificationEnum.STANDARD_CQ_CHECK_PH.getUpper()) {
						qualification = QUALIFIED;
					}
					technicalRequirement = CQQualitySpecificationEnum.STANDARD_CQ_CHECK_PH.getScope();
				} else {
					if (!FLAG.equals(error)
							&& Double.valueOf(error) >= CQQualitySpecificationEnum.STANDARD_CQ_CHECK.getLower()
							&& Double.valueOf(error) <= CQQualitySpecificationEnum.STANDARD_CQ_CHECK.getUpper()) {
						qualification = QUALIFIED;
					}
					technicalRequirement = CQQualitySpecificationEnum.STANDARD_CQ_CHECK.getScope();
				}
				/*
				 * else if (indexCode.equals(QualityProjectEnum.DO.getCode())) { if
				 * (!FLAG.equals(error) && Double.valueOf(error) >=
				 * CQQualitySpecificationEnum.STANDARD_CHECK_DO.getLower() &&
				 * Double.valueOf(error) <=
				 * CQQualitySpecificationEnum.STANDARD_CHECK_DO.getUpper()) { qualification =
				 * QUALIFIED; } technicalRequirement =
				 * CQQualitySpecificationEnum.STANDARD_CHECK_DO.getScope(); } else if
				 * (indexCode.equals(QualityProjectEnum.EC.getCode())) { if (!FLAG.equals(error)
				 * && Double.valueOf(error) >=
				 * CQQualitySpecificationEnum.STANDARD_CHECK_EC.getLower() &&
				 * Double.valueOf(error) <=
				 * CQQualitySpecificationEnum.STANDARD_CHECK_EC.getUpper()) { qualification =
				 * QUALIFIED; } technicalRequirement =
				 * CQQualitySpecificationEnum.STANDARD_CHECK_EC.getScope(); } else if
				 * (indexCode.equals(QualityProjectEnum.TUB.getCode())) { if
				 * (!FLAG.equals(error) && Double.valueOf(error) >=
				 * CQQualitySpecificationEnum.STANDARD_CHECK_TUB.getLower() &&
				 * Double.valueOf(error) <=
				 * CQQualitySpecificationEnum.STANDARD_CHECK_TUB.getUpper()) { qualification =
				 * QUALIFIED; } technicalRequirement =
				 * CQQualitySpecificationEnum.STANDARD_CHECK_TUB.getScope(); }
				 */
				VerificationOfStandardSample verificationOfStandardSample = new VerificationOfStandardSample();
				verificationOfStandardSample.setStationCode(stationCode);
				verificationOfStandardSample.setStationName(siteMap.get(stationCode).get("stationName").toString());
				verificationOfStandardSample.setBasinCode(siteMap.get(stationCode).get("basinn_basinnCode").toString());
				verificationOfStandardSample.setBasinName(siteMap.get(stationCode).get("basinn_basinnName").toString());
				verificationOfStandardSample.setAreaCode(siteMap.get(stationCode).get("area_areaCode").toString());
				verificationOfStandardSample.setAreaName("重庆市");
//				if ("40000000000001".equals(stationCode)) { // 水站1
//					verificationOfStandardSample.setStationName("水站1");
//					verificationOfStandardSample.setBasinCode("C001");
//					verificationOfStandardSample.setBasinName("长江流域");
//					verificationOfStandardSample.setAreaCode("001");
//					verificationOfStandardSample.setAreaName("测试区");
//				} else if ("40000000000002".equals(stationCode)) { // 水站2
//					verificationOfStandardSample.setStationName("水站2");
//					verificationOfStandardSample.setBasinCode("C001");
//					verificationOfStandardSample.setBasinName("长江流域");
//					verificationOfStandardSample.setAreaCode("001");
//					verificationOfStandardSample.setAreaName("测试区");
//				} else if ("40000000000003".equals(stationCode)) { // 污染源站点1
//					verificationOfStandardSample.setStationName("污染源站点1");
//					verificationOfStandardSample.setBasinCode("C001");
//					verificationOfStandardSample.setBasinName("长江流域");
//					verificationOfStandardSample.setAreaCode("001");
//					verificationOfStandardSample.setAreaName("测试区");
//				} else {
//					verificationOfStandardSample.setStationName("测试站");
//					verificationOfStandardSample.setBasinCode("A430100");
//					verificationOfStandardSample.setBasinName("测试流域");
//					verificationOfStandardSample.setAreaCode("001");
//					verificationOfStandardSample.setAreaName("测试区");
//				}
				verificationOfStandardSample.setIndexCode(indexCode);
				verificationOfStandardSample.setIndexName(QualityProjectEnum.getName(indexCode));
				verificationOfStandardSample.setIndexUnit(QualityProjectEnum.getUnit(indexCode));
				verificationOfStandardSample.setTime(timestamp);
				verificationOfStandardSample.setValue(value.toString());
				verificationOfStandardSample.setStandardSamplesValue(standardSamplesValue);
				verificationOfStandardSample.setError(error);
				verificationOfStandardSample.setTechnicalRequirement(technicalRequirement);
				verificationOfStandardSample.setQualification(qualification);
				verificationOfStandardSample.setDataFlag(dataFlag);
				try {
					iVerificationOfStandardSampleRepository.saveAndFlush(verificationOfStandardSample);
				} catch (Exception e) {
					Throwable cause = e.getCause();
					logger.info("@@@标样核查发生异常：" + ((org.hibernate.exception.ConstraintViolationException)cause).getSQLException().getMessage());
				}
			}
		}
		logger.info("@@@idList的大小" + idList.size());
		if (!idList.isEmpty()) {
			int part = idList.size() / 800; // 分批数
			logger.info("共有 ： " + idList.size() + "条");
			for (int i = 0; i <= part; i++) {
				int j = 800 * (i + 1);
				if (i == part) {
					j = idList.size();
				}
				logger.info("@@@开始执行updateCheckData");
				IDataReceivingService.updateCheckData(idList.subList(800 * i, j));
			}
			logger.info("@@@update执行结束");
		}
	}

	@Override
	public void createRecoveryData() {
		// 获取站点相关信息
		Map<String, Map<String, Object>> siteMap = this.getStationMsg();
		// 获取站点配置的质控参数信息
		List<Map<String, Map<String, Object>>> allMonthQualityControlRecoveryParam = IQualityControlSetService
				.currentMonthQualityControlRecoveryParam();
		ResultEntity resultEntity = IDataReceivingService.queryRecoveryData();
		if (resultEntity.getCode() == 1) {
			System.out.println("获取加标回收率初始数据失败！");
		}
		List<RecoveryData> list = objectMapperUtil.convertList(resultEntity, RecoveryData.class);
		List<String> idList = new ArrayList<String>();
		for (RecoveryData recoveryData : list) {
			String id = recoveryData.getId();
			idList.add(id);
			String stationCode = recoveryData.getMn();
			String indexCode = recoveryData.getFactorCode();
			String value = recoveryData.getWater(); // 测定值
			String addValue = recoveryData.getCheckData(); // 加标后水样测定值
			String addVolume = recoveryData.getVolume(); // 加标体积
			String addConcentration = recoveryData.getChromaValue(); // 加标浓度
			String waterSampleVolume = recoveryData.getDVolume(); // 加标后体积
			Date timestamp = recoveryData.getDataTime(); // 测试时间
			for (Map<String, Map<String, Object>> map : allMonthQualityControlRecoveryParam) {
				Map<String, Object> indexMap = map.get(stationCode);
				addConcentration = indexMap.get(indexCode + "addConcentration").toString();
				waterSampleVolume = indexMap.get(indexCode + "constantVolume").toString();
				if ((!"".equals(addConcentration) && addConcentration != null)
						|| (!"".equals(waterSampleVolume) && waterSampleVolume != null)) {
					break;
				}
			}
			// 修约测定值
//			if (value != null) {
//				value = QualityDataUtil.scaleData(indexCode, Double.valueOf(value)).toString();
//			}
			// 计算加标回收率
			String recoveryValue = FLAG;
			if (value != null && addValue != null && addVolume != null && addConcentration != null
					&& waterSampleVolume != null) {
				recoveryValue = CQQualityDataUtil.standardRecoveryRate(Double.valueOf(addValue), Double.valueOf(value),
						Double.valueOf(addVolume), Double.valueOf(addConcentration), Double.valueOf(waterSampleVolume));
			}
			// 判断是否合格
			String qualification = NO_QUALIFIED;
			if (!FLAG.equals(recoveryValue)) {
				if (Double.valueOf(recoveryValue) >= CQQualitySpecificationEnum.RECOVERY.getLower()
						&& Double.valueOf(recoveryValue) <= CQQualitySpecificationEnum.RECOVERY.getUpper()) {
					qualification = QUALIFIED;
				}
			}
			Recovery recovery = new Recovery();
			recovery.setStationCode(stationCode);
			recovery.setStationName(siteMap.get(stationCode).get("stationName").toString());
			recovery.setBasinCode(siteMap.get(stationCode).get("basinn_basinnCode").toString());
			recovery.setBasinName(siteMap.get(stationCode).get("basinn_basinnName").toString());
			recovery.setAreaCode(siteMap.get(stationCode).get("area_areaCode").toString());
			recovery.setAreaName("重庆市");
//			if ("40000000000001".equals(stationCode)) { // 水站1
//				recovery.setStationName("水站1");
//				recovery.setBasinCode("C001");
//				recovery.setBasinName("长江流域");
//				recovery.setAreaCode("001");
//				recovery.setAreaName("测试区");
//			} else if ("40000000000002".equals(stationCode)) { // 水站2
//				recovery.setStationName("水站2");
//				recovery.setBasinCode("C001");
//				recovery.setBasinName("长江流域");
//				recovery.setAreaCode("001");
//				recovery.setAreaName("测试区");
//			} else if ("40000000000003".equals(stationCode)) { // 污染源站点1
//				recovery.setStationName("污染源站点1");
//				recovery.setBasinCode("C001");
//				recovery.setBasinName("长江流域");
//				recovery.setAreaCode("001");
//				recovery.setAreaName("测试区");
//			} else {
//				recovery.setStationName("测试站");
//				recovery.setBasinCode("A430100");
//				recovery.setBasinName("测试流域");
//				recovery.setAreaCode("001");
//				recovery.setAreaName("测试区");
//			}
			recovery.setIndexCode(indexCode);
			recovery.setIndexName(QualityProjectEnum.getName(indexCode));
			recovery.setIndexUnit(QualityProjectEnum.getUnit(indexCode));
			recovery.setTime(timestamp);
			recovery.setValue(value);
			recovery.setAddValue(addValue);
			recovery.setAddConcentration(addConcentration);
			recovery.setAddVolume(addVolume);
			recovery.setWaterSampleVolume(waterSampleVolume);
			recovery.setRecoveryValue(recoveryValue);
			recovery.setError(recoveryValue);
			recovery.setTechnicalRequirement(CQQualitySpecificationEnum.RECOVERY.getScope());
			recovery.setQualification(qualification);
			try {
				iRecoveryRepository.saveAndFlush(recovery);
			} catch (Exception e) {
				Throwable cause = e.getCause();
				logger.info("@@@recovery发生异常：" + ((org.hibernate.exception.ConstraintViolationException)cause).getSQLException().getMessage());
			}
		}
		logger.info("@@@idList的大小" + idList.size());
		if (!idList.isEmpty()) {
			int part = idList.size() / 800; // 分批数
			logger.info("共有 ： " + idList.size() + "条");
			for (int i = 0; i <= part; i++) {
				int j = 800 * (i + 1);
				if (i == part) {
					j = idList.size();
				}
				logger.info("@@@开始执行updateRecoveryData");
				IDataReceivingService.updateRecoveryData(idList.subList(800 * i, j));
			}
			logger.info("@@@update执行结束");
		}
	}

	@SuppressWarnings("null")
	@Override
	public void createFiveParameterData() {
		// 获取站点相关信息
		Map<String, Map<String, Object>> siteMap = this.getStationMsg();
		// 获取站点配置的质控参数信息
		List<Map<String, Map<String, Object>>> weekQualityControlParam = IQualityControlSetService
				.currentWeekQualityControlParam();
//		从实时数据表中获取数据
//		ResultEntity resultEntity = IDataReceivingService.queryNoFlagRealData();
//		从check_data数据表中获取数据
		ResultEntity resultEntity = IDataReceivingService.queryCheckDataToFive();
		if (resultEntity.getCode() == 1) {
			System.out.println("获取实时分钟初始数据失败！");
		}
		List<CheckData> listOrg = objectMapperUtil.convertList(resultEntity, CheckData.class);
		List<CheckData> list = new ArrayList<CheckData>();
		List<String> project = new ArrayList<String>();
		project.add("w01001");// ph值
		project.add("w01010");// 温度
		project.add("w01009");// 溶氧
		project.add("w01014");// 电导率
		project.add("w01003");// 浊度
		listOrg.forEach(checkData -> {
			if (project.contains(checkData.getFactorCode())) {
				list.add(checkData);
			}
		});

		List<String> idList = new ArrayList<String>();
		for (CheckData checkData : list) {
			String id = checkData.getId();
			String stationCode = checkData.getMn();
			String indexCode = checkData.getFactorCode();
			String value = checkData.getCheckData(); // 测试值
//			Date timestamp = DateUtil.stringToDate(checkData.getDataTime(), DateUtil.DATE_FULL_STR); // 测试时间
			Date timestamp = checkData.getDataTime(); // 测试时间
			String standardSamplesValue = null; // 标准溶液浓度
			for (Map<String, Map<String, Object>> map : weekQualityControlParam) {
				Map<String, Object> indexMap = map.get(stationCode);
				if (indexMap == null) {
					continue;
				}
				standardSamplesValue = indexMap.get(indexCode) == null ? null : indexMap.get(indexCode).toString();
				if (!"".equals(standardSamplesValue) && standardSamplesValue != null) {
					break;
				}
			}
			// 计算误差
			String fiveError = FLAG;
			if (value != null && standardSamplesValue != null) {
				fiveError = CQQualityDataUtil.fiveParameterError(Double.valueOf(value),
						Double.valueOf(standardSamplesValue), indexCode);
			}
			// 判断是否合格
			String qualification = NO_QUALIFIED;
			String technicalRequirement = "";
			if (indexCode.equals(QualityProjectEnum.PH.getCode())) {
				if (!FLAG.equals(fiveError)
						&& Double.valueOf(fiveError) >= CQQualitySpecificationEnum.STANDARD_CHECK_PH.getLower()
						&& Double.valueOf(fiveError) <= CQQualitySpecificationEnum.STANDARD_CHECK_PH.getUpper()) {
					qualification = QUALIFIED;
				}
				technicalRequirement = CQQualitySpecificationEnum.STANDARD_CHECK_PH.getScope();
			} else if (indexCode.equals(QualityProjectEnum.WT.getCode())) {
				qualification = "";
			} else if (indexCode.equals(QualityProjectEnum.DO.getCode())) {
				if (!FLAG.equals(fiveError)
						&& Double.valueOf(fiveError) >= CQQualitySpecificationEnum.STANDARD_CHECK_DO.getLower()
						&& Double.valueOf(fiveError) <= CQQualitySpecificationEnum.STANDARD_CHECK_DO.getUpper()) {
					qualification = QUALIFIED;
				}
				technicalRequirement = CQQualitySpecificationEnum.STANDARD_CHECK_DO.getScope();
			} else if (indexCode.equals(QualityProjectEnum.EC.getCode())) {
				if (!FLAG.equals(fiveError)
						&& Double.valueOf(fiveError) >= CQQualitySpecificationEnum.STANDARD_CHECK_EC.getLower()
						&& Double.valueOf(fiveError) <= CQQualitySpecificationEnum.STANDARD_CHECK_EC.getUpper()) {
					qualification = QUALIFIED;
				}
				technicalRequirement = CQQualitySpecificationEnum.STANDARD_CHECK_EC.getScope();
			} else if (indexCode.equals(QualityProjectEnum.TUB.getCode())) {
				if (!FLAG.equals(fiveError)
						&& Double.valueOf(fiveError) >= CQQualitySpecificationEnum.STANDARD_CHECK_TUB.getLower()
						&& Double.valueOf(fiveError) <= CQQualitySpecificationEnum.STANDARD_CHECK_TUB.getUpper()) {
					qualification = QUALIFIED;
				}
				technicalRequirement = CQQualitySpecificationEnum.STANDARD_CHECK_TUB.getScope();
			}
//			else if(indexCode.equals(QualityProjectEnum..getCode())) {
//				
//			}
			FiveParameter fiveParameter = new FiveParameter();

//			if ("40000000000001".equals(stationCode) || "40000000000002".equals(stationCode) 
//					|| "40000000000003".equals(stationCode)) {
//				idList.add(id); // 只更新上述三个站点的标识
//				fiveParameter.setStationCode(stationCode);
//				fiveParameter.setStationName(siteMap.get(stationCode).get("stationName").toString());
//				fiveParameter.setBasinCode(siteMap.get(stationCode).get("basinn_basinnCode").toString());
//				fiveParameter.setBasinName(siteMap.get(stationCode).get("basinn_basinnName").toString());
//				fiveParameter.setAreaCode(siteMap.get(stationCode).get("area_areaCode").toString());
//				fiveParameter.setAreaName("重庆市");
//				fiveParameter.setIndexCode(indexCode);
//				fiveParameter.setIndexName(QualityProjectEnum.getName(indexCode));
//				fiveParameter.setIndexUnit(QualityProjectEnum.getUnit(indexCode));
//				fiveParameter.setTime(timestamp);
//				fiveParameter.setValue(value);
//				fiveParameter.setStandardSamplesValue(standardSamplesValue);
//				fiveParameter.setError(fiveError);
//				fiveParameter.setTechnicalRequirement(technicalRequirement);
//				fiveParameter.setQualification(qualification);
//				iFiveParameterRepository.saveAndFlush(fiveParameter);
//			}
			if (siteMap.get(stationCode) != null) {// 过滤站点未建的情况
				idList.add(id);
				fiveParameter.setStationCode(stationCode);
				fiveParameter.setStationName(siteMap.get(stationCode).get("stationName").toString());
				fiveParameter.setBasinCode(siteMap.get(stationCode).get("basinn_basinnCode").toString());
				fiveParameter.setBasinName(siteMap.get(stationCode).get("basinn_basinnName").toString());
				fiveParameter.setAreaCode(siteMap.get(stationCode).get("area_areaCode").toString());
				fiveParameter.setAreaName(siteMap.get(stationCode).get("area_areaName").toString());
				fiveParameter.setIndexCode(indexCode);
				fiveParameter.setIndexName(QualityProjectEnum.getName(indexCode));
				fiveParameter.setIndexUnit(QualityProjectEnum.getUnit(indexCode));
				fiveParameter.setTime(timestamp);
				fiveParameter.setValue(value);
				fiveParameter.setStandardSamplesValue(standardSamplesValue);
				fiveParameter.setError(fiveError);
				fiveParameter.setTechnicalRequirement(technicalRequirement);
				fiveParameter.setQualification(qualification);
				try {
					iFiveParameterRepository.saveAndFlush(fiveParameter);
				} catch (Exception e) {
					logger.info(e.getMessage());
					logger.info("@@@:保存五参异常[" + fiveParameter.toString() + "]" + e.getMessage());
				}
			}else {
				//将未建的站点的数据也标识为已读
				idList.add(id);
			}

		}
		logger.info("@@@idList的大小" + idList.size());
		if (!idList.isEmpty()) {
			int part = idList.size() / 800; // 分批数
			logger.info("共有 ： " + idList.size() + "条");
			for (int i = 0; i <= part; i++) {
				int j = 800 * (i + 1);
				if (i == part) {
					j = idList.size();
				}
				logger.info("@@@开始执行updateCheckDataToFive");
				IDataReceivingService.updateCheckDataToFive(idList.subList(800 * i, j));
			}
			logger.info("@@@update执行结束");
		}

	}

	@SuppressWarnings({ "null", "unchecked" })
	public void createMultipointLinearityData(List<MonthQualityMultipoint> monthQualityMultipoints,
			String stationCode) {
		MultipointLinearity multipointLinearity = new MultipointLinearity();

		// 拟合直线，计算相关系数
		List<Double> x = new ArrayList<Double>();
		List<Double> y = new ArrayList<Double>();

		ResultEntity resultEntity = ISiteManageService.queryStation(stationCode);
		if (resultEntity.getCode() == 1) {
			logger.info("站点数据获取失败");
		}
		Map<String, Object> valueMap = ResultEntityUtil.getDataListMap(resultEntity);

		multipointLinearity.setAreaCode(valueMap.get("AREA_ID").toString());
		multipointLinearity.setAreaName(valueMap.get("AREA_NAMES").toString());
		multipointLinearity.setStationName(valueMap.get("STATION_NAME").toString());
		multipointLinearity.setStationCode(valueMap.get("STATION_MN").toString());
		multipointLinearity.setBasinCode(valueMap.get("BASINN_CODE").toString());
		multipointLinearity.setBasinName(valueMap.get("BASINN_NAME").toString());
		multipointLinearity.setOperationName(valueMap.get("OPER_COMPANY_NAME").toString());
		multipointLinearity.setTime(new Date());

		for (MonthQualityMultipoint monthQualityMultipoint : monthQualityMultipoints) {

			if (monthQualityMultipoint.getCheckValue() != null) {
				x.add(monthQualityMultipoint.getStandardValue());
				y.add(monthQualityMultipoint.getCheckValue());
			}
			multipointLinearity.setIndexCode(monthQualityMultipoint.getIndexCode());
			multipointLinearity.setIndexName(monthQualityMultipoint.getIndexName());
			multipointLinearity.setIndexUnit(monthQualityMultipoint.getIndexUnit());

			if ("1".equals(monthQualityMultipoint.getTestPoint()) && monthQualityMultipoint.getCheckValue() != null) {
				multipointLinearity.setFirstPointValue(monthQualityMultipoint.getCheckValue().toString());
			} else if ("2".equals(monthQualityMultipoint.getTestPoint())
					&& monthQualityMultipoint.getCheckValue() != null) {
				multipointLinearity.setSecondPointValue(monthQualityMultipoint.getCheckValue().toString());
			} else if ("3".equals(monthQualityMultipoint.getTestPoint())
					&& monthQualityMultipoint.getCheckValue() != null) {
				multipointLinearity.setThirdPointValue(monthQualityMultipoint.getCheckValue().toString());
			} else if ("4".equals(monthQualityMultipoint.getTestPoint())
					&& monthQualityMultipoint.getCheckValue() != null) {
				multipointLinearity.setFourthPointValue(monthQualityMultipoint.getCheckValue().toString());
			} else if ("5".equals(monthQualityMultipoint.getTestPoint())
					&& monthQualityMultipoint.getCheckValue() != null) {
				multipointLinearity.setFifthPointValue(monthQualityMultipoint.getCheckValue().toString());
			} else if ("6".equals(monthQualityMultipoint.getTestPoint())
					&& monthQualityMultipoint.getCheckValue() != null) {
				multipointLinearity.setSixthPointValue(monthQualityMultipoint.getCheckValue().toString());
			}
		}
		if (TheleastsquaremethodUtils.correlationCoefficient(x, y) >= 0.98
				&& TheleastsquaremethodUtils.correlationCoefficient(x, y) <= 1) {
			multipointLinearity.setQualification("合格");
		} else {
			multipointLinearity.setQualification("不合格");
		}

		multipointLinearity.setRelatedCoefficient(TheleastsquaremethodUtils.correlationCoefficient(x, y) + "");
		// 将数据插入数据库
		try {
			IMultipointLinearityRepository.saveAndFlush(multipointLinearity);
		} catch (Exception e) {
			Throwable cause = e.getCause();
			if(cause instanceof org.hibernate.exception.ConstraintViolationException) {
				logger.info("@@@多点线性发生异常：" + ((org.hibernate.exception.ConstraintViolationException)cause).getSQLException().getMessage());
			}
		}
	}

	public ResultEntity createIntegratedInterventionDate(List<MonthQualityIntegrated> monthQualityIntegrateds,
			String stationCode) {
		// 获取站点信息
		ResultEntity resultEntity = ISiteManageService.queryStation(stationCode);
		if (resultEntity.getCode() == 1) {
			logger.info("站点数据获取失败");
		}
		Map<String, Object> valueMap = ResultEntityUtil.getDataListMap(resultEntity);

		for (MonthQualityIntegrated monthQualityIntegrated : monthQualityIntegrateds) {
			IntegratedIntervention integratedIntervention = new IntegratedIntervention();
			// 存入站点信息
			integratedIntervention.setAreaCode(valueMap.get("AREA_ID").toString());
			integratedIntervention.setAreaName(valueMap.get("AREA_NAMES").toString());
			integratedIntervention.setStationName(valueMap.get("STATION_NAME").toString());
			integratedIntervention.setStationCode(valueMap.get("STATION_MN").toString());
			integratedIntervention.setBasinCode(valueMap.get("BASINN_CODE").toString());
			integratedIntervention.setBasinName(valueMap.get("BASINN_NAME").toString());
			integratedIntervention.setOperationName(valueMap.get("OPER_COMPANY_NAME").toString());
			// 存入因子信息
			integratedIntervention.setIndexCode(monthQualityIntegrated.getIndexCode());
			integratedIntervention.setIndexName(monthQualityIntegrated.getIndexName());
			integratedIntervention.setIndexUnit(monthQualityIntegrated.getIndexUnit());
			integratedIntervention.setTechnicalCequirement("≤10%");
			// 存入时间
			integratedIntervention.setTime(monthQualityIntegrated.getSubmitTime());
			integratedIntervention.setAutomaticSamplingTime(monthQualityIntegrated.getOverIntegratedTime());// 自动采集时间-集成干预之后的时间
			integratedIntervention.setArtificiaSamplingTime(monthQualityIntegrated.getNotIntegratedTime());// 人工采集时间-集成干预之前的时间
			// 获取数值
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String automaticSamplingTime = formatter.format(integratedIntervention.getAutomaticSamplingTime());
			String srtificiaSamplingTime = formatter.format(integratedIntervention.getArtificiaSamplingTime());

			ResultEntity resultAutomaticSamplingValue = IDataReceivingService.queryHourDataByTimeStationCodeIndexCode(
					automaticSamplingTime, stationCode, integratedIntervention.getIndexCode());
			ResultEntity resultArtificiaSamplingValue = IDataReceivingService.queryHourDataByTimeStationCodeIndexCode(
					srtificiaSamplingTime, stationCode, integratedIntervention.getIndexCode());
			Map<String, Object> valueAutomaticSamplingValue;
			Map<String, Object> valueArtificiaSamplingValue;
			try {
				valueAutomaticSamplingValue = ResultEntityUtil
						.getDataListMap(resultAutomaticSamplingValue);				
			} catch (Exception e1) {
				e1.printStackTrace();
				return new ResultEntity(ResultStatus.ERROR, Constants.AFTER_INTEGRATE_DATA_ISNULL);
			}
			try {			
				valueArtificiaSamplingValue = ResultEntityUtil
						.getDataListMap(resultArtificiaSamplingValue);
			} catch (Exception e1) {
				e1.printStackTrace();
				return new ResultEntity(ResultStatus.ERROR, Constants.BEFORE_INTEGRATE_DATA_ISNULL);
			}
			integratedIntervention.setAutomaticSamplingValue(valueAutomaticSamplingValue.get("value").toString());
			integratedIntervention.setArtificiaSamplingValue(valueArtificiaSamplingValue.get("value").toString());

			// 计算误差
			BigDecimal automaticSamplingValue = new BigDecimal(valueAutomaticSamplingValue.get("value").toString());
			BigDecimal artificiaSamplingValue = new BigDecimal(valueArtificiaSamplingValue.get("value").toString());

			if (automaticSamplingValue.subtract(artificiaSamplingValue).compareTo(BigDecimal.ZERO) == 0) {
				integratedIntervention.setQualification("合格");
				integratedIntervention.setError("0.00%");
			} else {
				BigDecimal error = automaticSamplingValue.subtract(artificiaSamplingValue)
						.divide(automaticSamplingValue.add(artificiaSamplingValue), 4, BigDecimal.ROUND_HALF_UP);
				if (error.abs().compareTo(new BigDecimal("0.1")) == -1) {
					integratedIntervention.setQualification("合格");
				} else {
					integratedIntervention.setQualification("不合格");
				}
				DecimalFormat df = new DecimalFormat("0.00%");
				integratedIntervention.setError(df.format(error));
			}

			try {
				IIntegratedInterventionRepository.saveAndFlush(integratedIntervention);
			} catch (Exception e) {
				Throwable cause = e.getCause();
				logger.info("@@@集成干预发生异常：" + ((org.hibernate.exception.ConstraintViolationException)cause).getSQLException().getMessage());
			}
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.DEAL_SUCCESS);
	}

	public void createRealWaterSampleComparisonData(List<ArtificialData> artificialDatas) {
		String stationCode = null;
		for (ArtificialData artificialData : artificialDatas) {
			stationCode = artificialData.getMn();
		}
		// 获取站点信息
		ResultEntity resultEntity = ISiteManageService.queryStation(stationCode);
		if (resultEntity.getCode() == 1) {
			logger.info("站点数据获取失败");
		}
		Map<String, Object> valueMap = ResultEntityUtil.getDataListMap(resultEntity);

		for (ArtificialData artificialData : artificialDatas) {
			RealWaterSampleComparison realWaterSampleComparison = new RealWaterSampleComparison();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (QualityProjectEnum enu : QualityProjectEnum.values()) {
				if (enu.getCode().equals(artificialData.getFactorCode())) {
					// 站点信息
					realWaterSampleComparison.setAreaCode(valueMap.get("AREA_ID").toString());
					realWaterSampleComparison.setAreaName(valueMap.get("AREA_NAMES").toString());
					realWaterSampleComparison.setStationName(valueMap.get("STATION_NAME").toString());
					realWaterSampleComparison.setStationCode(valueMap.get("STATION_MN").toString());
					realWaterSampleComparison.setBasinCode(valueMap.get("BASINN_CODE").toString());
					realWaterSampleComparison.setBasinName(valueMap.get("BASINN_NAME").toString());
					realWaterSampleComparison.setOperationName(valueMap.get("OPER_COMPANY_NAME").toString());
					// 因子信息
					realWaterSampleComparison.setIndexCode(enu.getCode());
					realWaterSampleComparison.setIndexName(enu.getName());
					realWaterSampleComparison.setIndexUnit(enu.getUnit());
					realWaterSampleComparison.setTechnicalCequirement(enu.getTechnicalRequirement());
					realWaterSampleComparison.setArtificialValue(artificialData.getRealValue());
					realWaterSampleComparison.setAutomaticValue(artificialData.getTestValue());

					Date time = null;
					Date samplingTime = null;

					try {
						time = formatter.parse(artificialData.getTestDataTime());
						samplingTime = formatter.parse(artificialData.getRealDataTime());
					} catch (ParseException e) {
						e.printStackTrace();
					}

					realWaterSampleComparison.setTime(time);
					realWaterSampleComparison.setSamplingTime(samplingTime);

					BigDecimal artificialValue = new BigDecimal(realWaterSampleComparison.getArtificialValue());
					BigDecimal automaticValue = new BigDecimal(realWaterSampleComparison.getAutomaticValue());
					if ("pH".equals(enu.getName())) {
						BigDecimal error = artificialValue.subtract(automaticValue);
						error = error.divide(BigDecimal.ONE, 4, BigDecimal.ROUND_HALF_UP);
						realWaterSampleComparison.setError(error.toString());
						if (error.abs().compareTo(new BigDecimal("0.5")) == 1) {
							realWaterSampleComparison.setQualification("不合格");
						} else {
							realWaterSampleComparison.setQualification("合格");
						}

					} else if ("电导率".equals(enu.getName())) {
						BigDecimal error = (automaticValue.subtract(artificialValue)).divide(artificialValue, 4,
								BigDecimal.ROUND_HALF_UP);
						DecimalFormat df = new DecimalFormat("0.00%");
						realWaterSampleComparison.setError(df.format(error));
						if (error.abs().compareTo(new BigDecimal("0.05")) == 1) {
							realWaterSampleComparison.setQualification("不合格");
						} else {
							realWaterSampleComparison.setQualification("合格");
						}
					} else if ("叶绿素".equals(enu.getName())) {
						BigDecimal error = (automaticValue.subtract(artificialValue)).divide(artificialValue, 4,
								BigDecimal.ROUND_HALF_UP);
						DecimalFormat df = new DecimalFormat("0.00%");
						realWaterSampleComparison.setError(df.format(error));
						if (error.abs().compareTo(new BigDecimal("0.2")) == 1) {
							realWaterSampleComparison.setQualification("不合格");
						} else {
							realWaterSampleComparison.setQualification("合格");
						}
					} else {
						BigDecimal error = (automaticValue.subtract(artificialValue)).divide(artificialValue, 4,
								BigDecimal.ROUND_HALF_UP);
						DecimalFormat df = new DecimalFormat("0.00%");
						realWaterSampleComparison.setError(df.format(error));
						if (error.abs().compareTo(new BigDecimal("0.1")) == 1) {
							realWaterSampleComparison.setQualification("不合格");
						} else {
							realWaterSampleComparison.setQualification("合格");
						}
					}

				}
			}
			if (realWaterSampleComparison.getArtificialValue() != null) {

				try {
					IRealWaterSampleComparisonRepository.saveAndFlush(realWaterSampleComparison);
				} catch (Exception e) {
					Throwable cause = e.getCause();
					logger.info("@@@实际水样发生异常：" + ((org.hibernate.exception.ConstraintViolationException)cause).getSQLException().getMessage());
				}
			}

		}

	}

	
	
	@SuppressWarnings({ "unchecked", "unused" })
	public void sendWarnMessage() {
		// 获取当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		long nowTime = System.currentTimeMillis();
		Date date = new Date();

		// 获取站点相关信息
//		ResultEntity stationResult = ISiteManageService.queryStationInfo();
		ResultEntity stationResult = IDataReceivingService.getStationMn();
		Map<String, Object> stationMap = (Map<String, Object>) stationResult.getContent();
		List<String> stationList = (List<String>) stationMap.get("dataList");
		List<Map<String, Object>> warnList = WarnUtil.getWarnlist();
		Integer count = WarnUtil.getCount();
		for (String mn : stationList) {
			// 获取站点的报警信息
			logger.info("正在获取站点：" + mn + "的预警信息！");
			ResultEntity resultEntity = IDataReceivingService.queryRealTimeOverDate(mn);
			if (resultEntity != null) {
				Map<String, Object> dataMap = (Map<String, Object>) resultEntity.getContent();
				List<Map<String, Object>> warning = (List<Map<String, Object>>) dataMap.get("dataList");
				if (!warning.isEmpty()) {
					for (Map<String, Object> warn : warning) {
						if (!warnList.contains(warn)) {
							long dataTime = 0;
							try {
								dataTime = dateFormat.parse(warn.get("time").toString()).getTime();
							} catch (ParseException e) {
								e.printStackTrace();
							}
							
//							boolean b = false;
//							for(Map<String, Object> p : warnList) {
//								 b = p.containsValue(mn);
//							}
							//不重发服务重启后单例模式中没有的预警信息
							if (count > 0) {
								ResultEntity userIdResult = ISiteManageService
										.queryUserIdByStationMn(warn.get("mn").toString());
								Map<String, Object> userIdMap = (Map<String, Object>) userIdResult.getContent();
								List<String> userIds = (List<String>) userIdMap.get("dataList");
								for (String id : userIds) {
									ResultEntity userResult = ISysUserService.getUserById(id);
									SysUser sysUser = objectMapperUtil.convertObject(userResult, SysUser.class);
									String templateParam = null;

									/**
									 * 模版CODE: SMS_205810094 模版内容: ${recMan}您好！水环境综合信息化及决策支持系统通知：${time},
									 * 站点:{stationName},超标因子:${prijectName},当前值为：
									 * ${value}--(参考标准${threshold})，超标倍数${multiple}。 变量属性:
									 * recMan-其他；time-时间；prijectName-其他；value-其他；threshold-其他；multiple-其他；
									 * 
									 * 模版CODE: SMS_205810721 模版内容: 监测报警：${time}，${stationName}水站站
									 * ${prijectName}值为${value}， 已超标。 变量属性:
									 * time-时间；stationName-其他；prijectName-其他；value-其他；
									 * 
									 */
									String recMan = sysUser.getUserName();
									date.setTime(dataTime);
									String time = dateFormat.format(date);
									String stationName = warn.get("stationName").toString();
									String prijectName = warn.get("fName").toString();
									String value = warn.get("value").toString();

									// templateParam = "{\"recMan\":\"" + recMan + "\",\"time\":\"" + time +
									// "\",\"stationName\":\""
									// + stationName + "\",\"prijectName\":\"" + prijectName + "\",\"value\":\"" +
									// value
									// + "\",\"threshold\":\"" + threshold + "\",\"multiple\":\"" + multiple +
									// "\"}";

									templateParam = "{\"time\":\"" + time + "\",\"stationName\":\"" + stationName
											+ "\",\"prijectName\":\"" + prijectName + "\",\"value\":\"" + value + "\"}";

									if ("1".equals(sysUser.getWarner()) && !sysUser.getPhonenb().isEmpty()
											&& !templateParam.isEmpty() && count <= 1000) {
										SmsUtil.SendSms(templateParam, sysUser.getPhonenb());
										logger.info("短信已发送：模版CODE为 SMS_205810721 参数：" + templateParam + "(今日第" + count +"条)");
										count ++ ;
									}
								}
							}
							warnList.add(warn);
						}
					}
				}
			}

		}
		
		List<Map<String, Object>> delList = new ArrayList<Map<String,Object>>();
		
		for(Map<String, Object> v : warnList) {
			long startTime = 0;
			try {
				startTime = dateFormat.parse(v.get("time").toString()).getTime();
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			if((nowTime - startTime) > 12 * 60 * 60 * 1000) {
				delList.add(v);
			}
		}
		warnList.removeAll(delList);
		
	}

//	public static void main(String[] args) {
//		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//		long nowTime = System.currentTimeMillis();
//		Date date = new Date();
//        date.setTime(nowTime);
//		String time = dateFormat.format(date);
//		System.out.println(time);
//	}

	@SuppressWarnings("unchecked")
	public Map<String, Map<String, Object>> getStationMsg() {
		QueryParamDto queryParamDto = null;
		try {
			queryParamDto = JsonUtils.readJsonFromClassPath("/queryParam/siteQuery.json", QueryParamDto.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ResultEntity resultEntity = ISiteManageService.queryStation(queryParamDto);
		Map<String, Object> dataMap = (Map<String, Object>) resultEntity.getContent();
		List<Map<String, Object>> siteList = (List<Map<String, Object>>) dataMap.get("dataList");
		Map<String, Map<String, Object>> siteMap = new HashMap<>();
		for (Map<String, Object> map : siteList) {
			siteMap.put(map.get("stationMn").toString(), map);
		}
		return siteMap;
	}

}
